'use strict';
const { generateOrderCode } = require('../../../../util/generator.js');

module.exports = {
	/**
	 * getList
	 * @url client/order/kh/add 前端调用的url参数地址
	 * data 请求参数
	 * @param {String} templateId  模板ID 必传
	 * @param {string} orderType 订单类型 avatar：头像购买 template：模板购买 必传
	 * @param {String} payType 支付渠道，wxpay | alipay | ttpay 现阶段只支持微信 非必传 默认wxpay
	 * @param {String} platform 下单平台类型：mp-weixin、mp-alipay、mp-toutiao 现阶段只支持微信小程序 非必传 默认mp-weixin
	 */
	main: async (event) => {
		let { data = {}, userInfo, util, filterResponse, originalParam } = event;
		let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
		let { uid } = data;
		if (!['tool', 'goods'].includes(data.orderType)) {
			return { code: 400, msg: "购买类型错误！" };
		}
		
		// 生成支付订单号
		const transaction_id = generateOrderCode();
		let total_fee = null;
    let description = ''
    switch (data.orderType){
      case 'tool':
        // 查下工具信息
        let toolInfo = await vk.baseDao.findByWhereJson({
          dbName:"ai-tool",
          whereJson: {
            tool_id: data.extendData.tool_id,
          }
        });
        if (data.orderType === 'tool' && (!toolInfo || !toolInfo.price_config)) {
          return { code: 400, msg: "参数错误，请检查工具是否存在！" };
        }
        if (toolInfo.price_config.length > 0) {
          const priceConfig = toolInfo.price_config
          const selectPrice = priceConfig.find(item => item.key === data.extendData.priceKey)
          total_fee = selectPrice.price
          description = '购买工具--' + selectPrice.desc
        } else {
          return { code: 400, msg: "服务器异常，请稍后重试！" };
        }
        break;
      case 'goods':
        console.log(data.extendData.goods_id)
        let goodsInfo = await vk.baseDao.findByWhereJson({
          dbName:"ai-goods",
          whereJson: {
            _id: data.extendData.goods_id,
          }
        });
        console.log(goodsInfo)
        if (data.orderType === 'goods' && (!goodsInfo || !goodsInfo.price)) {
          return { code: 400, msg: "参数错误，请检查商品是否存在！" };
        }
        total_fee = goodsInfo.price
        description = '购买' + goodsInfo.goods_name
      default:
        break;
    }
		const order = {
			user_id: uid,
			template_id: data.templateId || '',
			total_fee: total_fee,
			order_type: data.orderType,
			pay_type: data.payType || 'wxpay', // 默认微信支付
			platform: data.platform || 'web', // 默认微信小程序平台下单
			status: 1, // 订单状态 默认待支付，1：待付款，2：已付款，3：退款审核中，4：退款中，5：已退款，-1已取消付款/退款，-2：退款拒绝，-3：退款失败
			is_refund: false,
			refund_amount: 0,
			create_time: new Date().getTime(),
			update_time: null,
			paid_time: null,
			refund_time: null,
			refund_desc: null,
			transaction_id, // 支付订单号
      extendData: data.extendData
		};
    console.log(order)
		// 插库
		const addId = await vk.baseDao.add({
			dbName: 'ai-orders',
			dataJson: order
		});
		const res = {
			code: 0,
			msg: "success",
			data: {
				total_fee: order.total_fee,
				out_trade_no: order.transaction_id,
				order_no: addId,
				description,
				type: data.notityType || 'goods'
			},
		};
		// 业务逻辑结束-----------------------------------------------------------
		return res;
	}
}
